import java.util.HashMap;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 九转苍翎
 * Date: 2025/8/26
 * Time: 19:16
 */
public class Solution {
    public int findMaxLength(int[] nums) {
        int maxLength = 0,sum = 0;
        HashMap<Integer, Integer> map = new HashMap<>();
        map.put(0,-1);//默认存在前缀和为0的情况
        for (int i = 0; i < nums.length; i++) {
            sum += (nums[i] == 0 ? -1 : 1);//计算当前位置前缀和
            if (map.containsKey(sum)) {
                maxLength = Math.max(maxLength, i - map.get(sum));
            }else {
                map.put(sum,i);
            }
        }
        return maxLength;
    }
    public static void main(String[] args) {
        Solution solution = new Solution();
        int maxLength = solution.findMaxLength(new int[]{0,1,1,1,1,1,0,0,0});
        System.out.println(maxLength);
    }
}